//
//  ViewController.m
//  04-UI
//
//  Created by Snow on 16/7/19.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "ViewController.h"
#import "Masonry.h"
#import <AVFoundation/AVFoundation.h>
#import "LrcParse.h"
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)AVAudioPlayer *player;
@property (nonatomic, strong) NSTimer *firstTimer;
@property (nonatomic, assign) CGFloat a;
@property (nonatomic, strong) NSTimer *secTimer;
@property (nonatomic, strong) UITableView *lrcTable;
@property (nonatomic, strong) LrcParse *lrcContent;
@property (nonatomic, assign) NSInteger currentRow;
@property (nonatomic, strong) UIImageView *imageOfCenter;
@property (nonatomic, strong) UILabel *labelOfLeft;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.a = 1;
    //播放器
    NSString *path = [[NSBundle mainBundle] pathForResource:@"IU-12月24日(D.ear Cover)" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    NSLog(@"%g", self.player.duration);
    self.player.numberOfLoops=10;
//  background
    UIImageView *imageOfbackgroud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"41_151008164557_5.jpg"]];
    [self.view addSubview:imageOfbackgroud];
    [imageOfbackgroud mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
    UIView *view = [UIView new];
    [self.view addSubview:view];
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.8;
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
    //SongName
    UILabel *labelOfSong = [UILabel new];
    [view addSubview:labelOfSong];
    [labelOfSong mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(self.view.mas_top).mas_equalTo(20);
        make.left.mas_equalTo(80);
        make.height.mas_equalTo(30);
    }];
    labelOfSong.text = @"12월24일-12月24日";
    labelOfSong.textAlignment = 1;
    labelOfSong.font = [UIFont systemFontOfSize:18];
    labelOfSong.textColor = [UIColor whiteColor];
    
    UIImageView *imageOfLeftButton = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Unknown"]];
    [view addSubview:imageOfLeftButton];
    [imageOfLeftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(20);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
    
    //labelOfSinger
    UILabel *labelOfSinger = [UILabel new];
    [view addSubview:labelOfSinger];
    [labelOfSinger mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.left.mas_equalTo(150);
        make.top.mas_equalTo(50);
        make.height.mas_equalTo(30);
    }];
    labelOfSinger.text = @"아이유(IU)";
    labelOfSinger.textAlignment = 1;
    labelOfSinger.textColor = [UIColor whiteColor];
    
    UIView *viewOfLeft = [UIView new];
    UIView *viewOfRight = [UIView new];
    [view addSubview:viewOfLeft];
    [view addSubview:viewOfRight];
    [viewOfLeft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(1);
        make.top.mas_equalTo(labelOfSong.mas_bottom).mas_equalTo(15);
        make.right.mas_equalTo(labelOfSinger.mas_left).mas_equalTo(-10);
    }];
    [viewOfRight mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(1);
        make.top.mas_equalTo(labelOfSong.mas_bottom).mas_equalTo(15);
        make.left.mas_equalTo(labelOfSinger.mas_right).mas_equalTo(10);
    }];
    viewOfLeft.backgroundColor = [UIColor whiteColor];
    viewOfRight.backgroundColor = [UIColor whiteColor];
    
    //imageOfButton
    UIImageView *imageOfMV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cell_mv_icon"]];
    [view addSubview:imageOfMV];
    [imageOfMV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(labelOfSinger.mas_bottom).mas_equalTo(10);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(20);
    }];
    
    UIImageView *imageOfSong = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"player_btn_sq_sel_normal"]];
    [view addSubview:imageOfSong];
    [imageOfSong mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(imageOfMV.mas_left).mas_equalTo(-10);
        make.top.mas_equalTo(labelOfSinger.mas_bottom).mas_equalTo(10);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(20);
    }];
    
    UIImageView *imageOfDTS = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"player_btn_dts_on_pressed"]];
    [view addSubview:imageOfDTS];
    [imageOfDTS mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(imageOfMV.mas_right).mas_equalTo(10);
        make.top.mas_equalTo(labelOfSinger.mas_bottom).mas_equalTo(10);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(20);
    }];
//  center picture
    self.imageOfCenter = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"41_151008164557_5.jpg"]];
    [self.view addSubview:self.imageOfCenter];
    [self.imageOfCenter mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(imageOfMV.mas_bottom).mas_equalTo(15);
        make.width.mas_equalTo(300);
        make.height.mas_equalTo(300);
    }];
    self.imageOfCenter.layer.masksToBounds = YES;
    self.imageOfCenter.layer.cornerRadius = 150;
    
    //UISlider
    UISlider *slider = [UISlider new];
    [view addSubview:slider];
    [slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_imageOfCenter.mas_centerX);
        make.width.mas_equalTo(250);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(_imageOfCenter.mas_bottom).mas_equalTo(80);
    }];
    [slider setMinimumTrackImage:[UIImage imageNamed:@"player_slider_playback_left"] forState:UIControlStateNormal];
    [slider setMaximumTrackImage:[UIImage imageNamed:@"player_slider_playback_right"] forState:UIControlStateNormal];
    [slider setThumbImage:[UIImage imageNamed:@"player_slider_playback_thumb"] forState:UIControlStateNormal];
    [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    slider.maximumValue = self.player.duration;
    slider.tag = 100;
    
    //定时器
    //定时器 让slider随player播放移动
    self.firstTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(changeTime) userInfo:nil repeats:YES];
    
    //转动第三种方法初始化动画
    [self initAnimatiom];
    //先不要让动画播放
    [self pauseLayer:self.imageOfCenter.layer];

    
    //time
    self.labelOfLeft = [UILabel new];
    UILabel *labelOfRightTime = [UILabel new];
    [view addSubview:self.labelOfLeft];
    [view addSubview:labelOfRightTime];
    [self.labelOfLeft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(5);
        make.right.mas_equalTo(slider.mas_left).mas_equalTo(5);
        make.centerY.mas_equalTo(slider.mas_centerY);
        make.height.mas_equalTo(40);
    }];
    [labelOfRightTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-5);
        make.left.mas_equalTo(slider.mas_right).mas_equalTo(5);
        make.centerY.mas_equalTo(slider.mas_centerY);
        make.height.mas_equalTo(40);
    }];

    self.labelOfLeft.text = @"00:00";
    labelOfRightTime.text = @"03:35";
    labelOfRightTime.textAlignment = 1;
    self.labelOfLeft.textAlignment = 1;
    self.labelOfLeft.textColor = [UIColor grayColor];
    labelOfRightTime.textColor = [UIColor grayColor];
    self.labelOfLeft.font = [UIFont systemFontOfSize:10];
    labelOfRightTime.font = [UIFont systemFontOfSize:10];
   
    //player
    UIButton *buttonOfPlay = [UIButton buttonWithType:UIButtonTypeSystem];
    [view addSubview:buttonOfPlay];
    [buttonOfPlay mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(slider.mas_bottom).mas_equalTo(-10);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(90);
        make.height.mas_equalTo(90);
    }];
    [buttonOfPlay setBackgroundImage:[UIImage imageNamed:@"hp_player_btn_play_highlight"] forState:UIControlStateNormal];
    [buttonOfPlay addTarget:self action:@selector(handlePlay:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *buttonOfLeft = [UIButton buttonWithType:UIButtonTypeSystem];
    [view addSubview:buttonOfLeft];
    [buttonOfLeft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(buttonOfPlay.mas_left).mas_equalTo(-10);
        make.centerY.mas_equalTo(buttonOfPlay.mas_centerY);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(60);
    }];
    
    [buttonOfLeft setBackgroundImage:[UIImage imageNamed:@"hp_player_btn_pre_highlight"] forState:UIControlStateNormal];
    
    UIButton *buttonOfRight = [UIButton buttonWithType:UIButtonTypeSystem];
    [view addSubview:buttonOfRight];
    [buttonOfRight mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(buttonOfPlay.mas_right).mas_equalTo(10);
        make.centerY.mas_equalTo(buttonOfPlay.mas_centerY);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(60);
    }];
    [buttonOfRight setBackgroundImage:[UIImage imageNamed:@"hp_player_btn_play_highlight"] forState:UIControlStateNormal];
    
    //flag
    NSArray *array = @[@"1", @"2", @"3", @"4", @"5"];
    for (NSInteger i = 0; i < 5; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:array[i]] forState:UIControlStateNormal];
        [view addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(buttonOfPlay.mas_bottom).mas_equalTo(10);
            make.bottom.mas_equalTo(self.view.mas_bottom).mas_equalTo(-10);
            make.left.mas_equalTo(self.view.mas_left).mas_equalTo((self.view.frame.size.width / 5) * i);
            make.width.mas_equalTo(self.view.frame.size.width / 5);
        }];
    }
    //歌词
    self.lrcTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 450, self.view.frame.size.width, 40) style:UITableViewStylePlain];
    [self.view addSubview:self.lrcTable];
    self.lrcTable.delegate = self;
    self.lrcTable.dataSource = self;
    self.lrcTable.backgroundColor = [UIColor clearColor];
    [self.lrcTable registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    self.lrcTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 解析歌词
    self.lrcContent = [[LrcParse alloc] init];
    [self.lrcContent parserLrc];
}

// 控制播放进度
- (void)sliderAction: (UISlider *)slider {
    NSLog(@"%f", slider.value);
    self.player.currentTime = slider.value;
    NSString *str = [NSString stringWithFormat:@"%f", slider.value / 60];
//    NSString *ing = [NSString stringWithFormat:@"%f", (slider.value % 60)];
    self.labelOfLeft.text = [str stringByAppendingString:@":"];
    
}
- (void)initAnimatiom {
    //创建一个绕z轴选择的动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //旋转一周
    animation.toValue = @(2*M_PI);
    //循环次数，尽量大
    animation.repeatCount = MAXFLOAT;
    //执行一次动画需要的时间
    animation.duration = 50.0f;
    [self.imageOfCenter.layer addAnimation:animation forKey:@"rotationAnimation"];
}

- (void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

- (void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}

- (void)handlePlay:(UIButton *)button
{
    [self.player play];
    CAAnimation * anim = [self.imageOfCenter.layer animationForKey:@"rotationAnimation"];
    if (anim == nil) {
        [self initAnimatiom];
    }else{
        [self resumeLayer:self.imageOfCenter.layer];
    }
    [button removeTarget:self action:@selector(handlePlay:) forControlEvents:UIControlEventTouchUpInside];
    [button addTarget:self action:@selector(handlePause:) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:[UIImage imageNamed:@"hp_player_btn_pause_highlight"] forState:UIControlStateNormal];
}

- (void)handlePause:(UIButton *)button
{
    [self.player pause];
    //暂停封面图片的旋转
    CAAnimation * anim = [self.imageOfCenter.layer animationForKey:@"rotationAnimation"];
    if (anim) {
        //暂停动画
        [self pauseLayer:self.imageOfCenter.layer];
    }
    [button removeTarget:self action:@selector(handlePause:) forControlEvents:UIControlEventTouchUpInside];
    [button addTarget:self action:@selector(handlePlay:) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:[UIImage imageNamed:@"hp_player_btn_play_highlight"] forState:UIControlStateNormal];
}
- (void)changeTime {
    UISlider *slider = (UISlider *)[self.view viewWithTag:100];
    slider.value = self.player.currentTime;
    
#pragma mark 歌词滚动
    // 先打印下音乐播到几分几秒
    CGFloat currentTime = self.player.currentTime;
    for (int i = 0; i < self.lrcContent.timeArray.count; i++) {
        NSArray *timeArray = [self.lrcContent.timeArray[i] componentsSeparatedByString:@":"];
        float lrcTime = [timeArray[0] intValue]*60 + [timeArray[1] floatValue];
        if (currentTime > lrcTime) {
            self.currentRow = i;
        } else
            break;
    }
    [self.lrcTable reloadData];
    [self.lrcTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.lrcContent.wordArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
    cell.textLabel.text = self.lrcContent.wordArray[indexPath.row];
    if (indexPath.row == self.currentRow) {
        cell.textLabel.textColor = [UIColor colorWithRed:0.18 green:0.8 blue:0.58 alpha:1];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
    } else {
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont systemFontOfSize:12];
    }
    cell.textLabel.textAlignment = 1;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.lineBreakMode = NSLineBreakByClipping;
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
